import { Monitor } from ".."
import { BlankScreenDetector } from "./blank-screen-detector"

export class BlankScreen {
    private monitor: Monitor
    private detector: BlankScreenDetector | null = null

    constructor(
        monitor: Monitor,
        private options = {}
    ) {
        this.monitor = monitor
    }

    public start(): void {
        this.detector = new BlankScreenDetector(result => {
            if (result.status === "error") {
                this.reportWhiteScreen(result)
            }
        }, this.options)

        this.detector.start()
    }

    public stop(): void {
        if (this.detector) {
            this.detector.stop()
            this.detector = null
        }
    }

    private reportWhiteScreen(result: any): void {
        const data = {
            type: "blank-screen",

            ...result,
            time: Date.now(),
            pageUrl: window.location.href,
            viewport: {
                width: window.innerWidth,
                height: window.innerHeight
            }
        }

        this.monitor.transport?.sendBlankScreen(data)
    }
}
